﻿using Chloe.SqlServer;
using SorketServer.HYModel;
using SorketServer.TBModel;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SorketServer
{
    public class MyJob
    {
        protected MsSqlContext NewHYDB()
        {
            string path = ConfigurationManager.AppSettings["FaceDB"].ToString();
            return new MsSqlContext(path);
        }
        /// <summary>
        /// 临时工
        /// </summary>
        /// <returns></returns>
        protected MsSqlContext NewTB1DB()
        {
            string path = ConfigurationManager.AppSettings["LinshiDB"].ToString();
            return new MsSqlContext(path);
        }
        /// <summary>
        /// 正式工
        /// </summary>
        /// <returns></returns>
        protected MsSqlContext NewTB2DB()
        {
            string path = ConfigurationManager.AppSettings["ZhengshiDB"].ToString();
            return new MsSqlContext(path);
        }
        public void Start()
        {
            //using (var db = NewTB2DB())
            //{
            //    db.Insert<HR_ATS_OriginalityCard>(new HR_ATS_OriginalityCard() {
            //        FCardDateTime=DateTime.Now,
            //        FCardID= "000051",
            //        FEmpID=Guid.Parse("CA6394E5-3F5B-47D9-9BE8-F9D5113ED2DD"),
            //        FStatus=1

            //    });
            //}

            DeleteLinshi();
            DeleteZhengshi();
            SynsLinshi();
            SynsZhengshi();
        }
        void DeleteLinshi()
        {
            var employees = new List<Guid>();
            using (var db = NewTB1DB())
            {
                employees = db.Query<HR_Base_Emp>().Where(c => c.Status != 1).Select(c => c.EM_ID).ToList();
            }
            using (var db = NewHYDB())
            {
                foreach (var userId in employees)
                {
                    var user = db.QueryByKey<UserInfo>(userId);
                    if (user != null)
                    {
                        var mobiles = db.Query<DepartMobileRL>().Where(cn => cn.DepartId == user.DepartId).Select(cn => cn.MobileId).ToList();
                        db.DeleteByKey<UserInfo>(userId);
                        foreach (var mobileId in mobiles)
                        {
                            SyncRL syncRL = new SyncRL()
                            {
                                Id = Guid.NewGuid(),
                                UserId = userId,
                                OperateType = 1,
                                MobileId = mobileId
                            };
                            db.Insert<SyncRL>(syncRL);
                        }
                    }
                }

            }
        }
        void DeleteZhengshi()
        {
            var employees = new List<Guid>();
            using (var db = NewTB2DB())
            {
                employees = db.Query<HR_Base_Emp>().Where(c => c.Status != 1).Select(c => c.EM_ID).ToList();
            }
            using (var db = NewHYDB())
            {
                foreach (var userId in employees)
                {
                    var user = db.QueryByKey<UserInfo>(userId);
                    if (user != null)
                    {
                        var mobiles = db.Query<DepartMobileRL>().Where(cn => cn.DepartId == user.DepartId).Select(cn => cn.MobileId).ToList();
                        db.DeleteByKey<UserInfo>(userId);
                        foreach (var mobileId in mobiles)
                        {
                            SyncRL syncRL = new SyncRL()
                            {
                                Id = Guid.NewGuid(),
                                UserId = userId,
                                OperateType = 1,
                                MobileId = mobileId
                            };
                            db.Insert<SyncRL>(syncRL);
                        }
                    }
                }

            }
        }

        void SynsLinshi()
        {
            var employees = new List<EmpositionDto>();
            using (var db = NewTB1DB())
            {
                var users = db.Query<HR_Base_Emp>().Where(c => c.Status == 1).ToList();
                var positionHis = db.Query<HM_EM_PositionHistory>().OrderByDesc(c => c.BeginDate).ToList();
                var positions = db.Query<ORG_Position>().ToList();
                var units = db.Query<ORG_Unit>().ToList();
                var linq = (from p in positions
                            join u in units on p.UnitID equals u.ID
                            select new UnitPosition()
                            {
                                PositionId = p.ID,
                                PositionName = p.Name,
                                UnitName = u.Name
                            }).ToList();

                foreach (var user in users)
                {
                    var temp = positionHis.Where(c => c.EM_ID == user.EM_ID);
                    var position = temp.GroupBy(c => c.PositionID).Select(g => new { Count = g.Count(), PositionId = g.Key }).FirstOrDefault(c => c.Count %2!=0);

                    if (position == null) continue;
                    var model = linq.FirstOrDefault(c => c.PositionId == position.PositionId);
                    if (model == null) continue;
                    employees.Add(new EmpositionDto()
                    {
                        Code = user.Code,
                        EM_ID = user.EM_ID,
                        Name = user.Name,
                        DepartName = model.UnitName,
                        PositionName = model.PositionName,
                        Status = user.Status,
                        PositionId = position.PositionId
                    });
                }

            }
            using (var db = NewHYDB())
            {
                foreach (var item in employees)
                {
                    var departId = Guid.NewGuid();
                    var depart = db.Query<Depart>().FirstOrDefault(c => c.Name == item.DepartName);
                    if (depart == null)
                    {
                        db.Insert<Depart>(new Depart() { Id = departId, Name = item.DepartName });
                    }
                    else
                    {
                        departId = depart.Id;
                    }
                    var user = db.Query<UserInfo>().FirstOrDefault(c => c.Id == item.EM_ID);
                    if (user == null)
                    {
                        db.Insert<UserInfo>(new UserInfo()
                        {
                            Id = item.EM_ID,
                            NickName = item.Name,
                            WorkNum = item.Code,
                            PositionId = item.PositionId,
                            RoleName = item.PositionName,
                            DepartId = departId,
                            IsZhengShi = 2
                        });
                    }
                    else
                    {
                        if (user.DepartId != departId)
                        {
                            ///删除旧的
                            var mobilesold = db.Query<DepartMobileRL>().Where(cn => cn.DepartId == user.DepartId).Select(cn => cn.MobileId).ToList();
                            foreach (var mobileId in mobilesold)
                            {
                                SyncRL syncRL = new SyncRL()
                                {
                                    Id = Guid.NewGuid(),
                                    UserId = user.Id,
                                    OperateType = 1,
                                    MobileId = mobileId
                                };
                                db.Insert<SyncRL>(syncRL);
                            }
                            //添加新的
                            var mobilesnew = db.Query<DepartMobileRL>().Where(cn => cn.DepartId == departId).Select(cn => cn.MobileId).ToList();
                            foreach (var mobileId in mobilesold)
                            {
                                SyncRL syncRL = new SyncRL()
                                {
                                    Id = Guid.NewGuid(),
                                    UserId = user.Id,
                                    OperateType = 0,
                                    MobileId = mobileId
                                };
                                db.Insert<SyncRL>(syncRL);
                            }
                            user.DepartId = departId;
                            user.PositionId = item.PositionId;
                            user.RoleName = item.PositionName;
                            db.Update<UserInfo>(user);

                        }
                    }
                }
            }
        }
        void SynsZhengshi()
        {
            var employees = new List<EmpositionDto>();
            using (var db = NewTB2DB())
            {
                var users = db.Query<HR_Base_Emp>().Where(c => c.Status == 1).ToList();
                var positionHis = db.Query<HM_EM_PositionHistory>().OrderByDesc(c => c.BeginDate).ToList();
                var positions = db.Query<ORG_Position>().ToList();
                var units = db.Query<ORG_Unit>().ToList();
                var linq = (from p in positions
                            join u in units on p.UnitID equals u.ID
                            select new UnitPosition()
                            {
                                PositionId = p.ID,
                                PositionName = p.Name,
                                UnitName = u.Name
                            }).ToList();
                foreach (var user in users)
                {
                    var temp = positionHis.Where(c => c.EM_ID == user.EM_ID);
                    var position = temp.GroupBy(c => c.PositionID).Select(g => new { Count= g.Count(),PositionId=g.Key }).FirstOrDefault(c=> c.Count % 2 != 0);
                    if (position == null) continue;
                    var model = linq.FirstOrDefault(c => c.PositionId == position.PositionId);
                    if (model == null) continue;
  
                    employees.Add(new EmpositionDto()
                    {
                        Code = user.Code,
                        EM_ID = user.EM_ID,
                        Name = user.Name,
                        DepartName = model.UnitName,
                        PositionName = model.PositionName,
                        Status = user.Status,
                        PositionId = position.PositionId
                    });
                }
            }
            using (var db = NewHYDB())
            {
                foreach (var item in employees)
                {

                    var departId = Guid.NewGuid();
                    var depart = db.Query<Depart>().FirstOrDefault(c => c.Name == item.DepartName);
                    if (depart == null)
                    {
                        db.Insert<Depart>(new Depart() { Id = departId, Name = item.DepartName });
                    }
                    else
                    {
                        departId = depart.Id;
                    }
                    var user = db.Query<UserInfo>().FirstOrDefault(c => c.Id == item.EM_ID);
                    if (user == null)
                    {
                        db.Insert<UserInfo>(new UserInfo()
                        {
                            Id = item.EM_ID,
                            NickName = item.Name,
                            WorkNum = item.Code,
                            PositionId = item.PositionId,
                            RoleName = item.PositionName,
                            DepartId = departId,
                            IsZhengShi = 1
                        });
                    }
                    else
                    {
                        if (user.DepartId != departId)
                        {
                            ///删除旧的
                            var mobilesold = db.Query<DepartMobileRL>().Where(cn => cn.DepartId == user.DepartId).Select(cn => cn.MobileId).ToList();
                            foreach (var mobileId in mobilesold)
                            {
                                SyncRL syncRL = new SyncRL()
                                {
                                    Id = Guid.NewGuid(),
                                    UserId = user.Id,
                                    OperateType = 1,
                                    MobileId = mobileId
                                };
                                db.Insert<SyncRL>(syncRL);
                            }
                            //添加新的
                            var mobilesnew = db.Query<DepartMobileRL>().Where(cn => cn.DepartId == departId).Select(cn => cn.MobileId).ToList();
                            foreach (var mobileId in mobilesold)
                            {
                                SyncRL syncRL = new SyncRL()
                                {
                                    Id = Guid.NewGuid(),
                                    UserId = user.Id,
                                    OperateType = 0,
                                    MobileId = mobileId
                                };
                                db.Insert<SyncRL>(syncRL);
                            }
                            user.PositionId = item.PositionId;
                            user.RoleName = item.PositionName;
                            user.DepartId = departId;
                            db.Update<UserInfo>(user);

                        }
                    }
                }
            }
        }
        void DeleteVisitor()
        {
            using (var db = NewHYDB())
            {
                var visitors = db.Query<Visitor>().Where(c => c.IsDelete == 0 && c.EndDate <= DateTime.Now).ToList();
                var mobileIds = db.Query<DepartMobileRL>().Where(cn => cn.DepartId == Guid.Empty).Select(cn => cn.MobileId).ToList();
                foreach (var id in mobileIds)
                {
                    foreach (var visitor in visitors)
                    {
                        SyncRL syncRL = new SyncRL()
                        {
                            Id = Guid.NewGuid(),
                            UserId = visitor.Id,
                            OperateType = 1,
                            MobileId = id,
                            UserType=1
                        };
                        visitor.IsDelete = 1;
                        db.Update<Visitor>(visitor);
                        db.Insert<SyncRL>(syncRL);
                    }
                  
                }
            }
        }
    }
}
